package org.amos.satoken.exception;

import cn.dev33.satoken.exception.DisableServiceException;
import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotPermissionException;
import cn.dev33.satoken.exception.NotSafeException;
import lombok.extern.slf4j.Slf4j;
import me.zhyd.oauth.exception.AuthException;
import org.amos.core.basic.vo.R;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author admin
 */
@Slf4j
@RestControllerAdvice
@Order(-99)
public class GlobalAuthExceptionHandler {

    @ExceptionHandler(NotLoginException.class)
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public R handleNotLoginError(NotLoginException e) {
        log.error("NotLoginException,msg={}", e.getMessage());

        String msg = "令牌失效";
        // 判断场景值，定制化异常信息
        if (e.getType().equals(NotLoginException.TOKEN_TIMEOUT)) {
            msg = "令牌已过期";
        }
        if (e.getType().equals(NotLoginException.BE_REPLACED)) {
            msg = "您已被顶下线";
        }
        if (e.getType().equals(NotLoginException.KICK_OUT)) {
            msg = "您已被踢下线";
        }

        return R.error(HttpStatus.UNAUTHORIZED.value(), msg);
    }

    @ExceptionHandler(NotSafeException.class)
    @ResponseStatus(HttpStatus.PRECONDITION_FAILED)
    public R handleNotLoginError(NotSafeException e) {
        return R.error(HttpStatus.PRECONDITION_FAILED.value(), "二级认证失败");
    }

    @ExceptionHandler(NotPermissionException.class)
    @ResponseStatus(HttpStatus.FORBIDDEN)
    public R handleNotLoginError(NotPermissionException e) {
        return R.error(HttpStatus.UNAUTHORIZED.value(), "该资源暂无权限");
    }

    @ExceptionHandler(DisableServiceException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public R handleError(DisableServiceException e) {
        log.error("认证异常", e);
        return R.error(e.getMessage());
    }

    @ExceptionHandler(AuthException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public R handleError(AuthException e) {
        log.error("认证异常", e);
        return R.error(e.getMessage());
    }

    @ExceptionHandler(DynamicAccessException.class)
    @ResponseStatus(HttpStatus.FORBIDDEN)
    public R<?> handleException(DynamicAccessException e) {
        log.error(e.getMessage(), e);
        return R.error(HttpStatus.FORBIDDEN.value(), "the interface has no access permission");
    }
}
